package com.exp.bookhouse.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.exp.bookhouse.mapper.BookMapper;
import com.exp.bookhouse.pojo.Book;
import com.exp.bookhouse.pojo.vo.BookVo;
import com.exp.bookhouse.pojo.vo.StockVo;
import com.exp.bookhouse.service.BookService;
import com.exp.bookhouse.util.AmountUtil;
import com.exp.bookhouse.util.UploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@PropertySource(value = "classpath:message.properties")
@Service
@Transactional
public class BookServiceImpl implements BookService {

    @Autowired
    private BookMapper bookMapper;

    @Autowired
    private UploadService uploadService;


    @Value("${book.carousel}")
    private String carousel;

    @Value("${nginx.port}")
    private String port;
    @Value("${nginx.host}")
    private String host;
    @Value("${nginx.group}")
    private String group;

    /**
     * 保存书籍
     * @param book
     * @return
     */
    @Override
    public int saveBook(Book book) throws Exception {
        String icon = "";
        String pic = "";
        book.setIcon(icon);
        book.setPic(pic);
        book.setPrice(AmountUtil.changeY2F(book.getPriceStr()));
        return bookMapper.insert(book);
    }

    /**
     * 根据分类id分页查询书籍
     * @param pageNum 当前页
     * @param pageSize 每页pageSize条数据
     * @param categoryId 分类id
     * @return
     */
    @Override
    public IPage<Book> queryBookByCategoryId(Integer pageNum, Integer pageSize, Integer categoryId) {
        IPage<Book> page = new Page<>(pageNum, pageSize);   //分页
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id",categoryId.longValue());
        IPage<Book> bookIPage = bookMapper.selectPage(page, wrapper);
        return bookIPage;
    }

    /**
     * 查询所有书籍
     * @return
     */
    @Override
    public List<Book> queryAllBook() {
        return bookMapper.selectList(null);
    }

    /**
     * 根据id更新书籍信息
     * @param book
     * @return
     */
    @Override
    public int updateBookById(Book book) {
        book.setPrice(AmountUtil.changeY2F(book.getPriceStr()));
        return bookMapper.updateById(book);
    }

    /**
     * 根据书名模糊查询纾解列表
     * @param pageNum 当前页
     * @param pageSize 每页条数
     * @param name 搜索条件
     * @return 书籍列表
     */
    @Override
    public IPage<Book> queryBookByName(Integer pageNum, Integer pageSize, String name) {
        IPage<Book> page = new Page<>(pageNum, pageSize);   //分页
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        wrapper.like("name",name);
        IPage<Book> bookIPage = bookMapper.selectPage(page, wrapper);
        return bookIPage;
    }

    //根据书名模糊查询，不分页
    @Override
    public List<Book> getBookByName(String name){
        List<Book> book = new ArrayList<>();
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        wrapper.like("name",name);
        book = bookMapper.selectList(wrapper);
        return book;
    }

    /**
     * 根据id查询库存
     * @param shopList
     * @return
     */
    @Override
    public List<StockVo> queryStockById(List<BookVo> shopList) {
        List<StockVo> stockVos = new ArrayList<>();
        for (BookVo bookVo : shopList) {
            StockVo stockVo = bookMapper.queryStockById(bookVo.getBookId());
            stockVos.add(stockVo);
        }
        return stockVos;
    }

    /**
     * 分页查询书籍列表
     * @param page
     * @param size
     * @return
     */
    @Override
    public IPage<Book> queryBookByPage(Integer page, Integer size) {
        IPage<Book> iPage = new Page<>(page,size);
        return bookMapper.selectPage(iPage,null);
    }

    /**
     * 根据id查询书籍
     * @param id
     * @return
     */
    @Override
    public Book queryBookById(Long id) {
        Book book = bookMapper.selectById(id);
        List<String> pics = new ArrayList<>();
        if(book.getPic() != null){
            String[] split = book.getPic().split(",");
            pics = Arrays.asList(split);
        }
        book.setPics(pics);
        return book;
    }

    /**
     * 更新书籍信息
     * @param id
     * @param file
     */
    @Override
    public void updateBookById(String id, MultipartFile[] file) throws IOException {
        StringBuilder sb = new StringBuilder();
        String icon = "";
        for(int i = 0; i < file.length; i++){
            String fillUrl = uploadService.uploadFile(file[i]);
//            String fillUrl = "http://"+host+"/"+group+"/"+uploadFile;
            if(i == 0){
                icon = fillUrl;
            }
            if(i == file.length - 1){
                sb.append(fillUrl);
            }else{
                sb.append(fillUrl+",");
            }
        }
        String pic = sb.toString();
        Book book1 = bookMapper.selectById(Long.parseLong(id));
        String pic1 = book1.getPic();

        Book book = new Book();
        book.setId(Long.parseLong(id));
        book.setIcon(icon);
        if("".equals(pic1) || pic1 == null){
            book.setPic(pic);
        }else{
            book.setPic(pic1+","+pic);
        }
        System.out.println(book);
        bookMapper.updateById(book);
    }

    /**
     * 删除指定书本的轮播图
     * @param id
     * @param url
     */
    @Override
    public Book deleteImage(Long id, String url) throws Exception {
        //更新数据库
        Book book = bookMapper.selectById(id);
        String pic = book.getPic();
        String[] split1 = pic.split(",");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < split1.length; i++) {
            if(!split1[i].equals(url)){
               sb.append(split1[i]+",");
            }
        }

        if(sb.length() > 0){
            String newPic = sb.toString();
            String newIcon = newIcon = newPic.substring(0,newPic.indexOf(","));
            newPic = sb.substring(0, sb.length()-1);
            book.setIcon(newIcon);
            book.setPic(newPic);
        }else{
            book.setPic("");
            book.setIcon("");
        }

        if(url.contains(group)){
            String[] split = url.split(".com/");
            uploadService.deleteFile(split[1]);   //删除服务器的图片
        }
        bookMapper.updateById(book);
        return book;
    }

    /**
     * 根据id删除书籍
     * @param id
     */
    @Override
    public void deleteBook(Long id) {
        bookMapper.deleteById(id);
    }
}
